"""
数据建模模块 - 高性能数据结构
"""
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
from datetime import datetime
import numpy as np
from collections import deque


@dataclass
class TraceEvent:
    """Trace事件数据结构"""
    timestamp: float  # 时间戳（微秒）
    event_type: str  # 事件类型
    thread_id: int  # 线程ID
    process_id: int  # 进程ID
    duration: float  # 持续时间（微秒）
    metadata: Dict[str, Any]  # 元数据
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'timestamp': self.timestamp,
            'event_type': self.event_type,
            'thread_id': self.thread_id,
            'process_id': self.process_id,
            'duration': self.duration,
            'metadata': self.metadata
        }


class RingBuffer:
    """环形缓冲区 - 用于百万级事件存储"""
    
    def __init__(self, capacity: int = 1000000):
        self.capacity = capacity
        self.buffer: deque = deque(maxlen=capacity)
        self._lock = None  # 线程锁占位
    
    def append(self, event: TraceEvent) -> None:
        """添加事件"""
        self.buffer.append(event)
    
    def extend(self, events: List[TraceEvent]) -> None:
        """批量添加事件"""
        self.buffer.extend(events)
    
    def get_range(self, start: int, end: int) -> List[TraceEvent]:
        """获取范围内的事件"""
        if start < 0 or end > len(self.buffer):
            return []
        return list(self.buffer)[start:end]
    
    def get_latest(self, count: int) -> List[TraceEvent]:
        """获取最新的N条事件"""
        return list(self.buffer)[-count:] if count <= len(self.buffer) else list(self.buffer)
    
    def clear(self) -> None:
        """清空缓冲区"""
        self.buffer.clear()
    
    @property
    def size(self) -> int:
        """当前大小"""
        return len(self.buffer)


class MetricsModel:
    """指标数据模型"""
    
    def __init__(self) -> None:
        self.events = RingBuffer()
        self._statistics: Dict[str, Any] = {}
    
    def add_event(self, event: TraceEvent) -> None:
        """添加单个事件"""
        self.events.append(event)
        self._update_statistics(event)
    
    def add_events_batch(self, events: List[TraceEvent]) -> None:
        """批量添加事件"""
        self.events.extend(events)
        for event in events:
            self._update_statistics(event)
    
    def _update_statistics(self, event: TraceEvent) -> None:
        """更新统计信息"""
        event_type = event.event_type
        if event_type not in self._statistics:
            self._statistics[event_type] = {
                'count': 0,
                'total_duration': 0.0,
                'avg_duration': 0.0,
                'min_duration': float('inf'),
                'max_duration': 0.0
            }
        
        stats = self._statistics[event_type]
        stats['count'] += 1
        stats['total_duration'] += event.duration
        stats['avg_duration'] = stats['total_duration'] / stats['count']
        stats['min_duration'] = min(stats['min_duration'], event.duration)
        stats['max_duration'] = max(stats['max_duration'], event.duration)
    
    def get_statistics(self) -> Dict[str, Any]:
        """获取统计信息"""
        return self._statistics.copy()
    
    def get_events_by_type(self, event_type: str) -> List[TraceEvent]:
        """按类型获取事件"""
        return [e for e in self.events.buffer if e.event_type == event_type]
    
    def get_time_series_data(self, window_size: int = 1000) -> np.ndarray:
        """获取时间序列数据（用于图表）"""
        latest_events = self.events.get_latest(window_size)
        if not latest_events:
            return np.array([])
        
        timestamps = np.array([e.timestamp for e in latest_events])
        return timestamps
    
    def clear(self) -> None:
        """清空数据"""
        self.events.clear()
        self._statistics.clear()


class DataAggregator:
    """数据聚合器 - 多源数据混合"""
    
    def __init__(self) -> None:
        self.sources: Dict[str, MetricsModel] = {}
        self.merged_model = MetricsModel()
    
    def register_source(self, source_name: str) -> MetricsModel:
        """注册数据源"""
        if source_name not in self.sources:
            self.sources[source_name] = MetricsModel()
        return self.sources[source_name]
    
    def merge_all_sources(self) -> None:
        """合并所有数据源"""
        all_events: List[TraceEvent] = []
        for source in self.sources.values():
            all_events.extend(list(source.events.buffer))
        
        # 按时间戳排序
        all_events.sort(key=lambda e: e.timestamp)
        
        # 更新合并模型
        self.merged_model.clear()
        self.merged_model.add_events_batch(all_events)
    
    def get_merged_model(self) -> MetricsModel:
        """获取合并后的模型"""
        return self.merged_model
